<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\general\LihuaCity;
use app\common\model\general\LihuaSlide;
use app\common\model\general\LihuaStore;
use app\common\model\goods\LihuaGoods;
use app\common\model\goods\LihuaStock;
use app\common\model\LihuaComment;
use app\common\model\LihuaActivity;
use app\common\model\LihuaHalfFree;
use app\common\model\LihuaSalesFree;
use app\common\model\LihuaMainPopup;
use app\common\model\LihuaBonusActlog;
use app\common\model\LihuaBonusAct;
use app\common\model\LihuaArticles; 
use app\common\model\LihuaVouchers; //现金抵用券
use app\admin\model\LihuaPrivateReq;
use app\admin\model\User;//用户表

use my\WxPay;
use fast\Http;
use fast\Random;
use think\Exception;
use think\Log;

/**
 * 首页分类门店评价
 */
class Index extends Api
{
    protected $noNeedLogin = [
        'index', 'category', 
        'city', 'store', 'getesnnum', 'store_info', 'getesnnum_new',
        'private_req_do', 'get_main_popup', 
        'check_popup_isneedshow', 'create_vouchers', 
        'test', 'get_city_phone', 'getGaoDeApi', 'getGaoDeApiKey',
    ]; 
    protected $noNeedRight = ['*'];
    /**
     * 首页
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city", type="string", required=true, description="城市名称或ID")
     * @ApiParams   (name="platform", type="string", required=false, description="平台")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1575716773","data":{"city_info":{"city_id":3,"city_name":"常州","am_time":["11:00","13:30"],"pm_time":["17:00","19:30"],"tel":"0519-88811711","min_price":0.01,"deliver_fee":0.01,"pay_types":["1","2","4"],"notice":"品质保证，绿色健康，吃的放心，欢迎订餐","enough":{"50":"10","100":"20"}},"slide_list":[{"title":"全力奋战，势必达成","pic":"https://lihua.czapi.cn/uploads/slide/2019/10/30525d9d7b9269b14.jpg","url":""},{"title":"母亲节","pic":"https://lihua.czapi.cn/uploads/slide/2019/10/39265d9d7d833cfdc.jpg","url":""}],"goods_list":[{"id":2341,"category_id":39,"name":"38元意式牛腩套餐","short_name":"牛腩","description":"意式牛腩+杏鲍菇腊肉+鱼香茄子+香油菠菜+红油鸭肫粒+玉米","pic":"http://image.lihua.com/images/newweb/2015/12/thumb_567e4db81f251.jpg","original_price":null,"price":38,"box_fee":1,"limit_num":0,"at_least":1,"is_alone_sale":1,"enable_stock":0},{"id":1070,"category_id":39,"name":"30元腊鸡块套餐","short_name":"腊鸡块","description":"腊鸡块+金针菇肉丝+莴笋鸡蛋+西兰花+椒盐花生","pic":"http://image.lihua.com/images/newweb/2015/11/thumb_564d781d37afb.JPG","original_price":null,"price":30,"box_fee":1,"limit_num":0,"at_least":1,"is_alone_sale":1,"enable_stock":0}]}})
     */
    public function index()
    {
        $city = $this->request->request('city', '');
        $plt  = strtolower($this->request->request('platform', 'app'));
        if (!$city || !in_array($plt, ['app','xcx'])) $this->error('参数错误');

        $city_info  = LihuaCity::getCityInfo($city);
        if (!$city_info) $this->error('当前城市暂未开放');
        if ($city_info['pay_types']) {
            $city_info['pay_types'] = $city_info['pay_types'][$plt];
        }

        $slide_list = LihuaSlide::getCitySlideList($city_info['city_id'], $plt);
        $goods_list = LihuaGoods::getCityGoodsList($city_info['city_id']);
        $activity_list = LihuaActivity::getActivityList($city_info['city_id']);
        if(count($activity_list)>0) {
            $activity_list = collection($activity_list)->toArray();
            foreach ($activity_list as $k => $v) {
                $activity_list[$k]['act_info'] = [];
                if ($v['type'] == 0) {//第二份半价
                    $heafActList = LihuaHalfFree::get($v['act_id']);
                    $activity_list[$k]['act_info'][] = $heafActList->toArray();
                }
                if ($v['type'] == 1) {//商品促销
                    $salesActList = LihuaSalesFree::get($v['act_id']);
                    $activity_list[$k]['act_info'][] = $salesActList->toArray();
                }
            }
        }

        // if( $this->auth->id == 29271 ){
        //     $city_info = ['1','2','3','4','6'];
        // }

        $this->success('OK', [
            'city_info'     => $city_info,
            'slide_list'    => $slide_list,
            'goods_list'    => $goods_list,
            'activity_list' => $activity_list,
            'history_ad'    => 1,
        ]);
    }

    //获取高德地图搜索POI信息
    public function getGaoDeApi()
    {
        $location  = $this->request->request('location', ''); //119.979855,31.791504
        $key = 'dac4395a48640ee00105d352598011eb';
        $url = "https://restapi.amap.com/v3/place/around";
		$ret = Http::get($url, ['key'=>$key, 'location'=>$location]);
		$res = json_decode($ret, true);
        $res['baidu'] = 0;
        if($res['info']=='USER_DAILY_QUERY_OVER_LIMIT'){
            $url = "https://restapi.amap.com/v5/place/around";
            $ret = Http::get($url, ['key'=>$key, 'location'=>$location]);
            $res = json_decode($ret, true);
        }
        if($res['status']==0){
            //高德失败后,调用百度
            // https://api.map.baidu.com/reverse_geocoding/v3/?ak=您的ak&output=json&coordtype=wgs84ll&location=31.225696563611,121.49884033194
            $gps_arr = explode(',', $location);
            $gps_data = $this->gaode_to_baidu($gps_arr[0],$gps_arr[1]);
            $location = $gps_data['latitude'].','.$gps_data['longitude'];
            $poi_types = '门址|行政地标|政府机构|公司企业|房地产|金融|交通设施|汽车服务|医疗|文化传媒|教育培训|运动健身|休闲娱乐|旅游景点|丽人|生活服务|购物|酒店|美食';
            $key = '72MXGZLSTPGWdH2r2Xw1RLXNNGwgujHP';
            $url = "https://api.map.baidu.com/reverse_geocoding/v3/";
            $ret = Http::get($url, ['ak'=>$key, 'output'=>'json', 'coordtype'=> 'wgs84ll', 'location' => $location ,'poi_types'=> $poi_types]);
            $res = json_decode($ret, true);
            $res['status'] = 1;
            $res['baidu'] = 1;
        }
		$this->success('ok', $res);
    }

    public function getGaoDeApiKey()
    {
        $keywords  = $this->request->request('keywords', '');
        $city_name  = $this->request->request('city_name', '');
        if (!$keywords || !$city_name ) {
            $this->error('参数错误');
        }
        //百度地图输入联想
        //https://api.map.baidu.com/place/v2/suggestion?query=天安门&region=北京&city_limit=true&output=json&ak=你的ak //GET请求
        $key = '72MXGZLSTPGWdH2r2Xw1RLXNNGwgujHP';
        $url = "https://api.map.baidu.com/place/v2/suggestion";
		$ret = Http::get($url, ['ak'=>$key, 'output'=>'json', 'region'=> $city_name , 'city_limit'=>true, 'query'=> $keywords ]);
		$res = json_decode($ret, true);
        if($res['message']!='ok') $this->error($res);

        //百度地图gps转高德地图
        foreach ($res['result'] as $k => $v) {
            $gd_gps = $this->baidu_to_gaode($v['location']['lng'], $v['location']['lat']);
            $res['result'][$k]['adname'] = $v['district'];
            $res['result'][$k]['pname'] = $v['province'];
            $res['result'][$k]['cityname'] = $v['city'];
            $res['result'][$k]['location'] = $gd_gps['longitude'].','.$gd_gps['latitude'];
        }
        $res['status'] = 1;
        $res['info'] = 'OK';
        $res['pois'] = $res['result'];
        $this->success('ok', $res);
    }

    //BD-09(百度)坐标转换成GCJ-02(火星，高德)坐标
    //@param $longitude 百度经度
    //@param $latitude 百度纬度
    public function baidu_to_gaode($longitude, $latitude)
    {
        $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        $x = $longitude - 0.0065;
        $y = $latitude - 0.006;
        $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
        $longitude = $z * cos($theta);
        $latitude = $z * sin($theta);
        $data['longitude'] = round($longitude, 6);
        $data['latitude'] = round($latitude, 6);
        return $data;
    }

    //GCJ-02(火星，高德)坐标转换成BD-09(百度)坐标
    //@param $longitude 高德经度
    //@param $latitude 高德纬度
    function gaode_to_baidu($longitude, $latitude){
        $x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        $x = $longitude;
        $y = $latitude ;
        $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
        $theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
        $longitude = $z * cos($theta) + 0.0065;
        $latitude = $z * sin($theta) + 0.006;
        // 保留小数点后六位
        $data['longitude'] = round($longitude, 6);
        $data['latitude'] = round($latitude, 6);
        return $data;
    }


    /**
     * 获取企业私定的企业数量
     */
    public function getesnnum()
    {
        $cityname = $this->request->request('cityname');
		//使用钱包余额支付订单
		$post_data = array();
		$ret = Http::post("https://private.lihua.com/api/enterprise/getesnnumber", $post_data);
		$res = json_decode($ret, true);
		$this->success('ok', $res);
    }

    /**
     * 获取企业私定的企业数量
     */
    public function getesnnum_new()
    {
        $cityname = $this->request->request('cityname');
		//使用钱包余额支付订单
		$post_data = array();
		$ret = Http::post("https://private.lihua.com/api/enterprise/getesnnumber", $post_data);
		$res = json_decode($ret, true);
		$this->success('ok', [
            'num' => $res['data'],
            'type' => 0, 
        ]);
    }
    /**
     * 分类
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID：3")
     * @ApiParams   (name="store_id", type="int", required=false, description="门店ID：18")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1567675144","data":{"category_list":[{"id":202,"name":"开心饮品（满35免送餐费）","goods":[{"id":50,"category_id":202,"name":"听装雪花啤酒","short_name":"雪花","description":"常温 净含量330ml（配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2018\/11\/thumb_5bdaa5ad5df8a.jpg","original_price":0,"price":5,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0}]},{"id":57,"name":"开心加料（单点不含餐具）","goods":[{"id":43,"category_id":57,"name":"蛋花汤料","short_name":"蛋花汤","description":"含汤碗 净含量8克（配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2016\/09\/thumb_57cfc743835e0.jpg","original_price":0,"price":2,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0},{"id":46,"category_id":57,"name":"雪菜汤料","short_name":"雪菜汤","description":"含汤碗 净含量3克（配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2016\/09\/thumb_57cfc709e088f.jpg","original_price":0,"price":1,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0},{"id":44,"category_id":57,"name":"三件套","short_name":"三件套","description":"三件套（不含汤勺，配餐产品，不单独售卖）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2018\/12\/thumb_5c0f521445dd8.JPG","original_price":0,"price":2.5,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0},{"id":45,"category_id":57,"name":"米饭","short_name":"白饭","description":"套餐里已含一份米饭（配餐产品，不单独售卖）（不配套餐具）","pic":"http:\/\/image.lihua.com\/images\/newweb\/2016\/09\/thumb_57cfc71baf78d.jpg","original_price":0,"price":3,"box_fee":0,"limit_num":0,"at_least":1,"is_alone_sale":2,"enable_stock":0}]},{"id":218,"name":"暖心砂锅","goods":[{"id":32797,"category_id":218,"name":"特别的爱砂锅","short_name":"特爱砂锅","description":"六荤六素全家福","pic":"http:\/\/image.lihua.com\/images\/newweb\/2019\/08\/thumb_5d5b494cbe158.jpg","original_price":0,"price":25,"box_fee":2,"limit_num":1,"at_least":1,"is_alone_sale":1,"enable_stock":0}]}]}})
     */
    public function category()
    {
        $city_id  = (int)$this->request->request('city_id', 0);
        $store_id = (int)$this->request->request('store_id', 0);
        if (!$city_id) $this->error('参数错误');
        $list = LihuaGoods::getCityCategoryGoodsList($city_id, $store_id);
        $this->success('OK', ['category_list' => $list]);
    }
    /**
     * 城市列表
     *
     * @ApiMethod   (POST)
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1566239128","data":{"city_list":[{"id":1,"name":"北京"},{"id":2,"name":"上海"},{"id":3,"name":"常州"},{"id":4,"name":"南京"},{"id":5,"name":"苏州"},{"id":6,"name":"无锡"},{"id":7,"name":"广州"}]}})
     */
    public function city()
    {
        $list = LihuaCity::getCityList();
        $this->success('OK', ['city_list' => $list]);
    }
    //get_city_phone 根据城市id获取该城市的客服电话
    public function get_city_phone()
    {
        $city_id = (int)$this->request->request('city_id', 0); //城市id
        $tel = LihuaCity::where('id', $city_id)->field('tel')->find();
        $this->success('OK', $tel);
    }
    /**
     * 获取当前城市企业私定的申请请求
     */
    public function private_req(){
        $phone = (int)$this->request->request('phone', 0); //联系号码
        $company = $this->request->request('company', ''); //企业名称
        $name = $this->request->request('name', ''); //客户名称
        $city_id = (int)$this->request->request('city_id', 0); //当前城市ID
        $city_name = $this->request->request('city_name', ''); //当前城市名称
        $num = (int)$this->request->request('num', 0); //企业用餐人数

        // 'phone' : '', //联系号码
        // 'company' : '', //企业名称
        // 'name' : '', //客户名称
        // 'city_id' : '', //当前城市ID
        // 'city_name' : '', //当前城市名称
        // 'event_city' : '', //申请城市名称
        // 'type' : '',//团餐类型

        $event_city = (int)$this->request->request('event_city', ''); //申请城市
        $type = $this->request->request('type', '私定申请'); //申请类型

        if(!$event_city) $event_city = $city_name;
        $city_arr = ['常州','北京','南京','苏州','无锡','上海','广州'];
        if(!in_array($event_city, $city_arr)){
            //如果存在，则直接进入城市，如果不存在则归类为常州
            $city_id = 3;
            $city_name = "常州";
        }
        $city_arr_s = ['',"bj","sh","cz","nj","sz","wx","gz"];
        $city_s = $city_arr_s[$city_id];
        
        if (!$company || !is_numeric($phone) || !$name || !$city_id || !$city_name ) {
            $this->error('参数错误');
        }
        if($num==0){
            // $this->error('请输入用餐人数');
        }
        if(strlen($company)<=3){
            $this->error('公司名称不能少于三个字符');
        }
        //一个用户一天只能申请三次
        $time1 = strtotime(date('Y-m-d ') . '00:00:00');
        $time2 = strtotime(date('Y-m-d ') . '23:59:59');
        //s
        $has_req = LihuaPrivateReq::where(['user_id'=> $this->auth->id, 'create_time' => ['>=', $time1] ])->count();
        $s = LihuaPrivateReq::getLastSql();
        if($has_req<3){
            $data = [
                'mobile' => $phone,
                'company' => $company,
                'consignee' => $name,
                'city_id' => $city_id,
                'city_name' => $city_name,
                'user_id' => $this->auth->id,
                'num' => $num,
                'city_name_req' => $event_city,
                'type' => $type
            ];
            $req = LihuaPrivateReq::create($data);

            // 申请成功需要把消息推送给客服
            $api2 = "http://cz.lihua.com/index.php?s=/WebApi/message/type/30/city/".$city_s."/telphone/".$phone.".html";
            $res2 = Http::get($api2);
            $this->success('OK', $req);
        }else{
            $this->error('一个账号只能提交三次申请', $s);
        }
    }
    /**
     * 企业私定请求数据处理
     */
    public function private_req_do(){
        $result = $this->request->request('result', ''); //处理结果
        $id = (int)$this->request->request('id', ''); //数据id
        if (!$result ) {
            $this->error('参数错误');
        }
        $data = LihuaPrivateReq::where(['id'=> $id])->find();
        $data->status = 1;
        $data->remark = $result;
        $s = $data->save();
        $this->success('OK', $s);
    }
    //检测是否需要弹出谈框活动
    public function check_popup_isneedshow()
    {
        // LihuaMainPopup
        $mainpopup_id = $this->request->request('mainpopup_id', ''); //谈框活动id
        $uid = (int)$this->request->request('uid', ''); //用户id
        if(!$mainpopup_id || !$uid ) $this->error('参数错误');
        $mainpopup_act = LihuaMainPopup::where(['id' => $mainpopup_id])->find();//参与历史记录
        // 获取当天日期
        $today = date('Y-m-d');
        if($mainpopup_act['type']==1){
            // 登录领取红包
            $bonus_act = LihuaBonusAct::where('id', $mainpopup_act['active_id'])->find();
            // 得到活动后判断该用户是否已经参加过/如果每日可领取，则需要带上日期判断
            // mainpopup_act
            $where = ['user_id'=> $uid, 'act_id'=> $bonus_act['id']];
            if($mainpopup_act['everyday']==1){
                $where['createtime_text'] = ['like', '%'.$today.'%'];
            }
            $is_get_res = LihuaBonusActlog::where($where)->find();
            if($is_get_res){
                // 已经领取过了
                $this->error('已参加');
            }else{
                $this->success('未参加');
            }
        }
        if($mainpopup_act['type']==2){
            // 获取活动文章详情
            $article_act = LihuaArticles::where('id', $mainpopup_act['article_id'])->find();
            $active_id_arr = [];
            if($article_act['open_active_id']!='') $active_id_arr[] = $article_act['open_active_id'];
            if($article_act['share_active_id']!='') $active_id_arr[] = $article_act['share_active_id'];
            if($article_act['button_active_id']!='') {
                $active_id_arr[] = $article_act['button_active_id'];
            };
            $where = ['user_id'=> $uid, 'act_id'=>['in', $active_id_arr]];
            if($mainpopup_act['everyday']==1){
                $where['createtime_text'] = ['like', '%'.$today.'%'];
            }
            $is_get_res = LihuaBonusActlog::where($where)->find();
            if($is_get_res){
                // 已经领取过了
                $this->error('已参加');
            }else{
                $this->success('未参加');
            }
        }
    }
    // 获取首页弹屏广告列表
    public function get_main_popup(){
        $city_id = $this->request->request('city_id', 0);
        $now = time();
        $list = LihuaMainPopup::where('city_id', $city_id)
                    ->where("'{$now}' BETWEEN `starttime` AND `endtime`")
                    ->field('id,name,pic,active_id,type,city_id,createtime,article_id')
                    ->select();
        // $s = LihuaMainPopup::getLastSql();
        $data = [];
        if($list) $data = $list;
        $this->success('OK', $data);
    }
    /**
     * 门店及库存
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=false, description="城市id")
     * @ApiParams   (name="lng", type="string", required=true, description="经度：119.957481")
     * @ApiParams   (name="lat", type="string", required=true, description="纬度：31.713501")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1571296846","data":{"store":{"id":18,"name":"湖塘","city_id":3},"stocks":{"1180":5000,"2228":200}}})
     */
    public function store() {
        $city_id = $this->request->request('city_id', 0);
        $lng     = $this->request->request('lng', '');
        $lat     = $this->request->request('lat', '');
        if (!is_numeric($lng) || !is_numeric($lat)) $this->error('参数错误');

        $store = LihuaStore::getPointStore($city_id, $lng, $lat);
        $city_id = $store['city_id'];
        $data['store']  = $store;
        $data['stocks'] = null;
        $data['city_id'] = $city_id;
        $citys = LihuaCity::where('id', $city_id)->field('name')->find();
        $data['city_name'] = $citys['name'];
        if ($store['id'] > 0) {
            $goods_ids  = LihuaGoods::where(['city_id' => $city_id, 'enable_stock' => 1])->column('id');
            if (!empty($goods_ids)) {
                $data['stocks'] = LihuaStock::whereIn('goods_id', $goods_ids)
                    ->where('store_id', $store['id'])
                    ->whereNotNull('num')
                    ->column('goods_id,num');
            }
        }
        $this->success('OK', $data);
    }

    //根据经纬度查询门店信息
    public function store_info() {
        $city_id = $this->request->request('city_id', 0);
        $lng     = $this->request->request('lng', '');
        $lat     = $this->request->request('lat', '');
        if (!is_numeric($lng) || !is_numeric($lat)) $this->error('参数错误');
        $store = LihuaStore::getPointStore($city_id, $lng, $lat);
        $city_id = $store['city_id'];
        $data['store']  = $store;
        $data['stocks'] = null;
        $data['city_id'] = $city_id;
        $citys = LihuaCity::where('id', $city_id)->field('name')->find();
        $data['city_name'] = $citys['name'];
        $this->success('OK', $data);
    }


    /**
     * 默认门店
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市id")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1570282516","data":{"id":25,"name":"丽华"}})
     */
    public function defstore() {
        $city_id  = $this->request->request('city_id', 0);
        if (!$city_id) $this->error('参数错误');

        $row = LihuaStore::where(['city_id' => $city_id, 'isdef' => 1])->field('id,name')->find();
        if (!$row) {
            $row = ['id' => 0, 'name' => ''];
        }
        $this->success('OK', $row);
    }
    /**
     * 评价列表
     *
     * @ApiMethod   (POST)
     * @ApiParams   (name="city_id", type="int", required=true, description="城市ID")
     * @ApiParams   (name="page", type="int", required=true, description="当前页，默认第1页")
     * @ApiParams   (name="page_size", type="int", required=false, description="每页条数，默认20条")
     * @ApiReturn   ({"code":1,"msg":"OK","time":"1571327639","data":{"page":1,"total":2,"page_size":20,"total_page":1,"list":[{"id":2,"nickname":"大帝","score":4.3,"content":"酸菜鸡真的很酸爽，吃了还想吃，赞","pics":["https:\/\/lihua.czapi.cn\/uploads\/goods\/2019\/10\/48345da884e09488c.jpg"],"time":"2019-10-14 12:31"},{"id":1,"nickname":"灰太狼","score":5,"content":"滑鸡饭分量足，真的好好吃","pics":["https:\/\/lihua.czapi.cn\/uploads\/goods\/2019\/10\/20725d9efea561b3e.jpg","https:\/\/lihua.czapi.cn\/uploads\/goods\/2019\/10\/56775da8853c519a2.jpg"],"time":"2019-10-11 19:17"}]}})
     */
    public function comment()
    {
        $city_id   = (int)$this->request->post('city_id');
        if (!$city_id) $this->error('参数错误');
        $page      = max(1, (int)$this->request->post('page'));
        $page_size = (int)$this->request->post('page_size') ? : 20;
        $data      = [
            'page'       => $page,
            'total'      => 0,
            'page_size'  => $page_size,
            'total_page' => 0,
            'list'       => []
        ];

        $where = ['city_id' => $city_id, 'status' => 1];
        $total = LihuaComment::where($where)->count();
        if ($total) {
            $data['total']      = $total;
            $data['total_page'] = ceil($total/$page_size);
            $res = LihuaComment::where($where)
                ->field('id,nickname,content,goods_score,courier_score,service_score,pics,create_time')
                ->order('id', 'desc')->page($page, $page_size)->select();
            $list = [];
            foreach ($res as $k => $v) {
                $score  = round(($v['goods_score'] + $v['courier_score'] + $v['service_score']) / 3, 1);
                $list[] = [
                    'id' => $v['id'],
                    'nickname' => $v['nickname'],
                    'score'    => $score,
                    'content'  => htmlentities($v['content']),
                    'pics'     => explode(',', $v['pics']),
                    'time'     => date('Y-m-d H:i', $v['create_time']),
                ];
            }
            $data['list'] = $list;
        }

        $this->success('OK', $data);
    }
    /**
     * 生成现金抵用券   
     * */
    public function create_vouchers(){

        $city_id    = (int)$this->request->request('city_id', 0);//城市ID
        $num        = (int)$this->request->request('num', 0); //份数
        $remark     = $this->request->request('remark', ''); //备注信息
        $consignee  = $this->request->request('consignee', ''); //经办人
        $section    = $this->request->request('section', ''); //部门信息
        $mobile     = $this->request->request('mobile', ''); //手机号
        $start_day  = $this->request->request('start_day', ''); //开始有效期
        $end_day    = $this->request->request('end_day', ''); //结束有效期
        $price      = $this->request->request('price', 0); //面值
        $type       = $this->request->request('type', 0); //使用类型

        if (!$city_id || !$num || !$remark || !$mobile || !$start_day || !$end_day || !$price){
            if(!$city_id) $this->error('请选择城市');
            if(!$num) $this->error('请输入份数');
            if(!$remark) $this->error('请输入备注信息');
            // if(!$mobile) $this->error('请充值手机号');
            if(!$start_day) $this->error('请选择优惠券起始时间');
            if(!$end_day) $this->error('请选择优惠券过期时间');
            if(!$price) $this->error('请选择优惠券面值');
        } 

        $users_id = 0;

        if(!!$mobile){
            //根据手机号获取用户信息
            $users = User::where(['mobile'=> $mobile])->find();
            if(!$users) $this->error('充值失败，暂无用户信息');
            $users_id = $users['id'];
        }

        $sn = "";
        $res_arr = [];
        for( $i=0; $i<$num; $i++ ){
            $sn = strtoupper(Random::alnum(10));
            $data = [
                'sn' => $sn,
                'city_id' => $city_id,
                'user_id' => $users_id,
                'start_date' => $start_day,
                'end_date' => $end_day,
                'status' => 0,
                'price' => $price,
                'create_time' => time(),
                'update_time' => time(),
                'remark' => $remark, //备注信息
                'consignee' => $consignee,
                'section' => $section,
                'type'  => $type,
            ];
            $res = LihuaVouchers::insert($data);
            $data['mobile'] = $mobile;
            $res_arr[] = $data;
        }
        $this->success('OK', $res_arr);
    }
    /**
     * 测试
     */
    public function test(){
        $xml   = "msgType=wx.notify&payTime=2021-07-20+10%3A47%3A06&buyerCashPayAmt=3900&connectSys=UNIONPAY&sign=176A86ADAACEE4D1293238250BE15351A461FC2E78FB27F4FE5DC87F658ACE36&merName=%E5%B8%B8%E5%B7%9E%E4%B8%BD%E5%8D%8E%E5%BF%AB%E9%A4%90%E9%9B%86%E5%9B%A2%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&mid=898320458141154&invoiceAmount=3900&settleDate=2021-07-20&billFunds=%E7%8E%B0%E9%87%91%3A3900&buyerId=otdJ_uP74ptc4h2LjKMeUNKMnEz8&mchntUuid=2d9081bc7394a692017394cbf14d480c&tid=D0111704&instMid=MINIDEFAULT&fu=JBuj&receiptAmount=3900&couponAmount=0&targetOrderId=4200001158202107206694280741&signType=SHA256&billFundsDesc=%E7%8E%B0%E9%87%91%E6%94%AF%E4%BB%9839.00%E5%85%83%E3%80%82&subBuyerId=o_mYZ0a1E8UGPSxiEOJVNWdyX0Fc&orderDesc=%E5%B8%B8%E5%B7%9E%E4%B8%BD%E5%8D%8E%E5%BF%AB%E9%A4%90%E9%9B%86%E5%9B%A2%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&seqId=22586693540N&merOrderId=10F1_2107380732044218_1418159573&targetSys=WXPay&bankInfo=%E5%BB%BA%E8%AE%BE%E9%93%B6%E8%A1%8C%28%E5%80%9F%E8%AE%B0%E5%8D%A1%29&totalAmount=3900&createTime=2021-07-20+10%3A47%3A01&buyerPayAmount=3900&notifyId=df715982-b6f9-46c3-94c0-7e8fe6a36939&subInst=100200&status=TRADE_SUCCESS";
		$wxpay = new WxPay();
		
        $res   = $wxpay->xmlstr_to_array_unionpay($xml);
        $this->success('OK', $res);
    }
}
